
// 21.合并两个有序链表
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode *phead = new ListNode , *tail = phead;
        ListNode *cur1 = list1 , *cur2 = list2;
        while(cur1 || cur2)
        {
            if(cur2 && (!cur1 || cur1->val > cur2-> val))            // cur2的元素只更小
            {
                tail->next = cur2;
                tail = tail->next;
                cur2 = cur2->next;
            }
            else 
            {
                tail->next = cur1;
                tail = tail->next;
                cur1 = cur1->next;
            }
        }
        tail->next = nullptr;
        return phead->next;
    }
};